package com.lecture.java8.node.tmp;

import java.util.ArrayList;
import java.util.List;

/**
 * @author luyn
 * @version 1.0
 * @description
 * @date 2022/7/4 16:56
 */
public class ForestNodeManager {

    //森林的所有节点
    private List<Permission> list;

    //森林的父节点ID
    private List<Integer> parentIds = new ArrayList<>();

    public ForestNodeManager(List<Permission> items) {
        this.list = items;
    }

    /***
     * @description 根据节点id获取一个节点
     * @author luyn
     * @date 2022/7/4 16:59
     * @param id id
     * @return com.lecture.java8.node.INode
    **/
    public Permission getTreeNodeAt(Integer id) {
        for (Permission forestNode : list) {
            if (forestNode.getId().longValue() == id.longValue()) {
                return forestNode;
            }
        }
        return null;
    }

    /***
     * @description 增加父节点ID
     * @author luyn
     * @date 2022/7/4 17:00
     * @param parentId 父节点id
     * @return void
    **/
    public void addParentId(Integer parentId) {
        parentIds.add(parentId);
    }

    /***
     * @description 获取树的根节点（一个森林对应多棵树）
     * @author luyn
     * @date 2022/7/4 17:02
     * @return java.util.List<T>
    **/
    public List<Permission> getRoot() {
        List<Permission> roots = new ArrayList<>();
        for (Permission forestNode : list) {
            if (forestNode.getPid() == 0 || parentIds.contains(forestNode.getId())) {
                roots.add(forestNode);
            }
        }
        return roots;
    }
}
